﻿using System.Collections.Generic;
using UnityEngine;

namespace DragBagSystem
{
    /// <summary>
    /// 背包
    /// 
    /// 背包栏功能：
    /// 1.可以加入并显示物品
    /// 2.可以移出物品
    /// 
    /// 背包物体功能：
    /// 1.可以将物品收纳到物品栏
    /// 2.物品能够拖拽出来，松开后物品自动复位
    /// 3.可以交换物品在物品栏的位置
    /// </summary>
    public class Bag : MonoBehaviour, IBag
    {
        public static Bag Instance
        {
            get => instance;
        }
        private static Bag instance;

        private void Awake()
        {
            instance = this;
        }

        /// <summary>
        /// 背包栏列表
        /// </summary>
        [SerializeField]private List<BagGrid> bagGrids = new List<BagGrid>();

        /// <summary>
        /// 背包总栏数
        /// </summary>
        public int BagGridCount => bagGrids.Count;
        
        /// <summary>
        /// 物体加入背包
        /// </summary>
        /// <param name="item"></param>
        /// <param name="grid"></param>
        /// <returns></returns>
        public static bool AddBagItem(IBagItem item, BagGrid grid)
        {
            return grid.AddBagItem(item);
        }
        /// <summary>
        /// 物品加入背包
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static bool AddBagItem(IBagItem item)
        {
            Bag bag = Instance;
            for (int i=0; i<bag.bagGrids.Count; ++i)
            {
                if (bag.bagGrids[i].IsEmpty)
                {
                    return AddBagItem(item, bag.bagGrids[i]);
                }
            }
            return false;
        }
        /// <summary>
        /// 物品移出背包
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static bool RemoveBagItem(IBagItem item)
        {
            var targetGrid = item.CurGrid();
            if (targetGrid != null)
            {
                return targetGrid.RemoveBagItem();
            }
            return false;
        }
        /// <summary>
        /// 物品移除背包并且销毁掉
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static bool RemoveAndDestroyBagItem(IBagItem item)
        {
            var targetGrid = item.CurGrid();

            if (targetGrid != null)
            {
                item.SetDestroyFlag(true);
                if (targetGrid.RemoveBagItem())
                {
                    //移除成功可以销毁
                    Destroy(item.Self());
                }
                else
                {
                    //移除失败的话不能进行销毁
                    item.SetDestroyFlag(false);
                }
                return true;
            }
            return false;
        }
    }
}

